package com.vidmt.api.modules.sys.auth.pwdstrategy;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vidmt.api.common.utils.Blowfish;
import com.vidmt.api.modules.sys.auth.DefaultReversPwdStrategy;

public class BlowfishStrategy extends DefaultReversPwdStrategy {
	private static Logger log = LoggerFactory.getLogger(BlowfishStrategy.class);
	private static Map<String, Blowfish> blCache = new HashMap<>();

	private static Blowfish getBlowfish(String keyString) {
		Blowfish cypher = blCache.get(keyString);
		if (cypher == null) {
			cypher = new Blowfish(keyString);
			blCache.put(keyString, cypher);
		}
		return cypher;
	}
	@Override
	protected String getPlainPwd(String rawkey, String ecryptedpwd) {
		try {
			Blowfish cypher = getBlowfish(rawkey);
			return cypher.decryptString(ecryptedpwd);
		} catch (UnsupportedOperationException uoe) {
			log.error("blowfish解码错误", uoe);
			return null;
		}
	}

	@Override
	public String getAlg() {
		return "bf";
	}

	@Override
	public String getCyphered(String key, String plainpwd) {
		try {
			Blowfish bf = getBlowfish(key);
			return bf.encryptString(plainpwd);
		} catch (UnsupportedOperationException uoe) {
			log.error("blowfish解码错误", uoe);
			throw new IllegalStateException(uoe);
		}
	}
}
